/*
 * @lc app=leetcode.cn id=2 lang=cpp
 *
 * [2] 两数相加
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

#include "include.h"

struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};
 
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int currentPosSum = 0;
        bool nextPosAdd = false;
        
        // new ListNode(0, nullptr)
        ListNode* res = nullptr;
        ListNode* end = nullptr;

        while (l1 or l2 or nextPosAdd){
            currentPosSum = nextPosAdd? 1:0;
// printf("in %d %d %d\n", l1->val, l2->val, currentPosSum);
            // traverse 2 list
            if (l1){
                currentPosSum += l1->val;
                l1 = l1->next;
            }
            if (l2){
                currentPosSum += l2->val;
                l2 = l2->next;
            }
            
            // check add
            if (currentPosSum>=10){
                currentPosSum -= 10;
                nextPosAdd = true;
            } else{
                nextPosAdd = false;
            }

// if (l1 and l2)
// printf("all %d %d %d\n", l1->val, l2->val, currentPosSum);            
            // get res lsit
            ListNode* newPos = new ListNode(currentPosSum, nullptr);
            if (res){
                end->next = newPos;
                end = newPos;
            } else{
                res = newPos;
                end = res;
            }
        }

        return res;
    }
};
// @lc code=end

